/*
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.fieldscope.api;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Represents a field group in a schema.
 * 
 * @author Travis Keep
 */
public class FieldGroup {
  
  private final long id;
  private final String name;
  private final List<Field> fields;
  
  /**
   * ID of this field group as known by fieldscope server.
   */
  public long getId() {
    return id;
  }

  /**
   * Name of this field group. This can be displayed to user in UI form.
   */
  public String getName() {
    return name;
  }
  
  /**
   * The fields in this field group.
   * Returned list cannot be modified.
   */
  public List<Field> getFields() {
    return fields;
  }
  
  @Override
  public String toString() {
    return String.format("{id=%d, name=%s, fields=%s", id, name, fields);
  }
  
  static List<FieldGroup> fromJSON(JSONArray json) throws JSONException {
    List<FieldGroup> result = new ArrayList<FieldGroup>(json.length());
    for (int i = 0; i < json.length(); i++) {
      result.add(singleFromJSON(json.getJSONObject(i)));
    }
    return result;
  }
  
  private FieldGroup(long id, String name, List<Field> fields) {
    this.id = id;
    this.name = name;
    this.fields = fields;
  }

  private static FieldGroup singleFromJSON(JSONObject jsonObject) throws JSONException {
    long id = jsonObject.getLong("id");
    String name = jsonObject.getString("label");
    JSONArray fieldsJSON = jsonObject.getJSONArray("fields");
    return new FieldGroup(id, name, Collections.unmodifiableList(Field.fromJSON(fieldsJSON)));
  }

}
